<template>
  <a-modal :width="1200" v-model:visible="showDetail" title="交货单确认出库" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="purchase-order-detail">
      <div class="bill-info">
        <div class="flex-c" style="margin-bottom: 10px">
          <p style="margin-right: 20px; width: 220px">
            <span class="label">交货单号：</span>
            <span class="highlight">{{ detailInfo.billNo }}</span>
          </p>
          <p style="margin-right: 20px; width: 220px">
            <span class="label">创建人：</span>
            <span>{{ detailInfo.createUname }}</span>
          </p>
          <p style="margin-right: 20px; width: 220px">
            <span class="label">创建时间：</span>
            <span>{{ $setTime(detailInfo.gmtCreate) }}</span>
          </p>
          <span class="label" style="width: 170px; text-align: right">是否需要扣减本地仓库存：</span>
          <a-select v-model="detailInfo.deductionType" placeholder="" style="width: 240px">
            <a-option :value="0" label="不需要" />
            <a-option :value="1" label="需要" />
          </a-select>
        </div>
        <div class="flex-c">
          <p style="margin-right: 20px; width: 220px">
            <span class="label">采购方：</span>
            <span>{{ detailInfo.companyName }}</span>
          </p>
          <p style="margin-right: 20px; width: 220px">
            <span class="label">收货仓：</span>
            <span>{{ detailInfo.warehouseName }}（{{ detailInfo.warehouseCode }}）</span>
          </p>
          <p style="margin-right: 20px; width: 220px">
            <span class="label">供应商：</span>
            <span>{{ detailInfo.supplierName }}（{{ detailInfo.supplierCode }}）</span>
          </p>
          <template v-if="detailInfo.deductionType == 1">
            <span class="label" style="width: 170px; text-align: right">本地交货仓库：</span>
            <a-select v-model="outWarehouse" value-key="warehouseCode" allow-search placeholder="" style="width: 240px">
              <a-option v-for="(item, i) in useBaseData.warehouseList" :key="i" :value="item" :label="item.warehouseName" />
            </a-select>
          </template>
        </div>
      </div>
      <div class="purchase-detail-order">
        <a-table class="table-two-line show-border-table" ref="tableRef" :data="detailInfo.billItems" :scroll="{ x: '100%', y: '100%' }" size="mini" :pagination="false">
          <template #columns>
            <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template #cell="{ record, rowIndex }">
                <!-- 产品 -->
                <div v-if="item.dataIndex == 'sku'" class="flex-c">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="50" height="50" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                  <a-popover position="bottom">
                    <template #content>
                      <div style="max-width: 400px">
                        <p>品名：{{ record.productName }}</p>
                        <p>SKU：{{ record.sku }}</p>
                        <p>SPU：{{ record.spu }}</p>
                        <p>类目：{{ record.cateName }}</p>
                        <p style="margin-bottom: 20px">规格：{{ getProductSpecs(record) }}</p>
                        <p v-for="(prop, k) in record.purchaseSpecsArr" :key="k">
                          <span>{{ prop.name }}：</span>
                          <span>{{ getStrVal(prop.purchaseValue) }}</span>
                        </p>
                      </div>
                    </template>
                    <div style="margin-left: 5px; flex: 1">
                      <p class="highlight">{{ record.sku }}</p>
                      <TextLimit :val="getProductSpecs(record)" :rows="1" />
                    </div>
                  </a-popover>
                </div>
                <!-- 交货数 -->
                <div v-else-if="item.dataIndex == 'deliveryAmt'" class="cell flex-c" style="width: 80px">
                  <a-input-number :precision="0" :min="0" v-model="record.deliveryAmt" style="width: 60px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'deliveryAmt')" />
                </div>
                <!-- 主材重量 -->
                <div v-else-if="item.dataIndex == 'materialWeight'" class="cell flex-c" style="width: 80px">
                  <a-input-number :precision="0" :min="0" v-model="record.materialWeight" style="width: 60px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'materialWeight')" />
                </div>
                <!-- 材质金额 -->
                <span v-else-if="item.dataIndex == 'materialAmount'">￥{{ (Number(record.materialWeight || 0) * Number(record.materialPrice || 0)).toFixed(2) }}</span>
                <!-- 产品金额 -->
                <span v-else-if="item.dataIndex == 'productAmount'">￥{{ (Number(record.deliveryAmt || 0) * Number(record.productPrice || 0)).toFixed(2) }}</span>
                <!-- 工费 -->
                <span v-else-if="item.dataIndex == 'laborAmount'">￥{{ (Number(record.deliveryAmt || 0) * Number(record.laborPrice || 0)).toFixed(2) }}</span>
                <!-- 其他费用 -->
                <div v-else-if="item.dataIndex == 'otherAmount'" class="cell flex-c" style="width: 80px">
                  <a-input-number :precision="0" :min="0" v-model="record.otherAmount" style="width: 60px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'otherAmount')" />
                </div>
                <!-- 合计金额 -->
                <span v-else-if="item.dataIndex == 'totalAmount'">￥{{ getTotalAmount(record).toFixed(2) }}</span>
                <!-- 税率 -->
                <template v-else-if="item.dataIndex == 'rate'">
                  <p>
                    <span>{{ Number(record.rate || 0) }}</span>
                    <span>%</span>
                  </p>
                  <p class="highlight">{{ record.priceType === 1 ? '含税' : '不含税' }}</p>
                </template>
                <!-- 单件货值 -->
                <span v-else-if="item.dataIndex == 'value'">￥{{ getTotalValue(record).toFixed(2) }}</span>
                <p v-else-if="['materialPrice', 'laborPrice', 'productPrice'].includes(item.dataIndex)">￥{{ record[item.dataIndex] }}</p>
                <a-popconfirm v-else-if="item.dataIndex == 'handle'" content="确定是否移除?" @ok="detailInfo.billItems.splice(rowIndex, 1)" type="error">
                  <a-button type="text">移除</a-button>
                </a-popconfirm>
                <p v-else>{{ record[item.dataIndex] }}</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <div style="text-align: right; margin-top: 10px"> 注意：如果需要扣减本地库存的，则确认出库之后，保留记录事后异步执行出库操作。 </div>
    </div>
    <template #footer>
      <a-space>
        <a-button class="gray-outline" @click="closedDialog">取消</a-button>
        <a-button type="primary" @click="submitData()" :loading="submitLoading">确认出库</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { getDeliveryInfo, outboundPurchaseDelivery } from '@/api/purchaseApplication'
  import { parseJson, getStrVal } from '@/utils'
  import { Message } from '@arco-design/web-vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { cloneDeep } from 'lodash-es'
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentId: {
      type: String,
    },
  })
  onMounted(() => {
    useBaseData.getWareHouseList()
  })
  const tableColumns: Array<any> = [
    {
      title: '产品',
      dataIndex: 'sku',
      width: 160,
    },
    {
      title: '采购单号',
      dataIndex: 'purchaseNo',
      width: 120,
    },
    {
      title: '采购员',
      dataIndex: 'purchaseUname',
      width: 60,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseAmt',
      width: 60,
    },
    {
      title: '已收货数',
      dataIndex: 'deliveryRealAmt',
      tip: '该采购已经签收的数量',
      width: 70,
    },
    {
      title: '未交货数',
      dataIndex: 'deliveryStayAmt',
      tip: '未交货数=采购数量-已收货数-已交货未签收数-截单数',
      width: 70,
    },

    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      width: 60,
    },

    {
      title: '产品单价',
      dataIndex: 'productPrice',
      width: 60,
    },
    {
      title: '工费单价',
      dataIndex: 'laborPrice',
      width: 60,
    },
    {
      title: '本次交货数',
      dataIndex: 'deliveryAmt',
      tip: '本次交货数=未交货数+（未交货数*0.3向上取整），--未交货数*0.3如果<=2则默认为3，也就是说供应商可以多发3件以上的货。',
      width: 100,
    },
    {
      title: '交货材质重(g)',
      dataIndex: 'materialWeight',
      tip: '交货材质重量是只本次交货材质净重量（该值针对的是首饰等以贵金属作为原材料的产品）',
      width: 100,
    },
    {
      title: '材质金额',
      dataIndex: 'materialAmount',
      tip: '材质金额=交货材质重量*材质单价',
      width: 70,
    },
    {
      title: '产品金额',
      dataIndex: 'productAmount',
      tip: '产品金额=产品单价*本次交货数',
      width: 70,
    },
    {
      title: '工费',
      dataIndex: 'laborAmount',
      tip: '工费=工费单价*本次交货数',
      width: 70,
    },
    {
      title: '其他费用',
      dataIndex: 'otherAmount',
      tip: '其他费用：本次交货产生的其他费用',
      width: 100,
    },
    {
      title: '合计金额',
      dataIndex: 'totalAmount',
      tip: '合计金额=材质金额+产品金额+工费+其他费用',
      width: 80,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 60,
    },
    {
      title: '单件货值',
      dataIndex: 'value',
      tip: '含税货值=合计金额/本次交货数不含税货值={合计金额-（合计金额-税率）}/本次交货数',
      width: 80,
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 80,
    },
  ]

  const useBaseData = useBaseDataStore()
  const showDetail = ref(props.isShow)
  const detailInfo = ref<any>({})
  const submitLoading = ref(false)
  const outWarehouse = ref<any>()

  // 关闭
  function closedDialog() {
    showDetail.value = false
    emit('closed')
  }

  // 获取详情
  async function getDetail() {
    if (!props.currentId) return
    const res: any = await getDeliveryInfo({ id: props.currentId })
    detailInfo.value = res?.data || {}
    if (detailInfo.value.outWarehouseCode) {
      outWarehouse.value = {
        warehouseCode: detailInfo.value.outWarehouseCode,
        outWarehouseName: detailInfo.value.outWarehouseName,
      }
    }
  }
  getDetail()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 确认
  async function submitData() {
    if (detailInfo.value.deductionType.value === 1 && !outWarehouse.value?.id) {
      Message.error('请选择本地交货仓库')
      return false
    }
    if (!detailInfo.value?.billItems?.length) {
      Message.error('最少需要一个明细')
      return false
    }

    let _params: any = cloneDeep(detailInfo.value)
    if (detailInfo.value.deductionType.value === 1) {
      _params.outWarehouseCode = outWarehouse.value.warehouseCode
      _params.outWarehouseName = outWarehouse.value.warehouseName
    }

    let flag = false
    _params.billItems = detailInfo.value.billItems.map((item: any) => {
      if (!item.deliveryAmt) {
        flag = true
      }
      return {
        billId: item.billId,
        id: item.id,
        materialWeight: item.materialWeight,
        deliveryAmt: item.deliveryAmt,
        otherAmount: item.otherAmount,
        purchaseId: item.purchaseId,
        purchaseItemId: item.purchaseItemId,
        remark: item.remark,
        settleType: item.settleType,
      }
    })
    if (flag) {
      Message.error('本次交货数必填')
      return
    }
    submitLoading.value = true
    const res: any = await outboundPurchaseDelivery(_params)
    submitLoading.value = false
    if (res) {
      Message.success('确认出库成功')
      emit('success')
      closedDialog()
    }
  }
  //设置全局
  async function setGlobal(item: any, key: string) {
    detailInfo.value.billItems.forEach((el: any) => {
      el[key] = item[key]
    })
  }
  // 获取合计金额
  function getTotalAmount(row: any) {
    let materialAmount = Number(row.materialWeight || 0) * Number(row.materialPrice || 0)
    let productAmount = Number(row.deliveryAmt || 0) * Number(row.productPrice || 0)
    let laborAmount = Number(row.deliveryAmt || 0) * Number(row.laborPrice || 0)
    let otherAmount = Number(row.otherAmount || 0)
    return materialAmount + productAmount + laborAmount + otherAmount
  }
  // 获取单件货值
  function getTotalValue(row: any) {
    let totalAmount = getTotalAmount(row)
    let rateAmount = row.priceType === 0 ? 0 : (totalAmount * Number(row.rate || 0)) / 100
    return row.deliveryAmt ? (totalAmount - rateAmount) / row.deliveryAmt : 0
  }
</script>

<style lang="less" scoped>
  .purchase-order-detail {
    height: calc(84vh - 160px);
    display: flex;
    flex-direction: column;
    .bill-info {
      padding: 5px 10px;
      background-color: var(--color-neutral-2);
      margin-bottom: 5px;
      border: 1px solid var(--color-neutral-3);
      .label {
        color: #999;
      }
    }
    .purchase-detail-order {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .edit-icon {
      font-size: 16px;
      margin-left: 5px;
      cursor: pointer;
    }
  }
  :deep(.arco-table) {
    .arco-table-cell {
      padding: 2px 5px;
    }
    .arco-select-view-single {
      padding: 0 5px;
    }
    .arco-input-wrapper {
      padding: 0 5px;
    }
    .arco-select-view-value {
      font-size: 12px !important;
      min-height: 26px;
    }
    .arco-input {
      font-size: 12px !important;
    }
  }
</style>
